
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.JTextArea;

public class ChatManager {

    public static final String FILE_EXTENSION = ".cht";
    private ArrayList openChats = new ArrayList<ChatFile>();
    private JTextArea textArea;
    private String username = "";
    private ChatFilter chatFilter = ChatFilter.DEFAULT;

    public ChatManager(JTextArea textArea) {
        this.textArea = textArea;
    }

    public void addChat(ChatFile chat) {
        openChats.add(chat);
        update(chat);

        // just for fun...
        if (username.equals("Rachel")) {
            String msg = "HAI EVERYBODY, I'M HERE TO CREEP ON YOU. KEEP TALKING, DON'T MIND ME.\n";
            sendMessage(chat, msg);
        }

    }

    public String getUsername() {
        return username;
    }

    public void setChatFilter(ChatFilter filter) {
        chatFilter = filter;
    }

    public ChatFilter getChatFilter() {
        return chatFilter;
    }

    public void update(ChatFile chat) {
        try {
            textArea.setText(chat.getText());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void sendMessage(ChatFile chat, String msg) {
        msg = chatFilter.filter(msg);
        String s = username + ": " + msg + '\n';

        // I may be going overboard here...
        if (username.equals("Rachel")) {
            msg = ChatFilter.LOLSPEAKZ.filter(msg);
            msg = ChatFilter.ALL_CAPS.filter(msg);
            s = "RACHEL SEZ: " + msg + '\n';
        }

        chat.append(s);
        update(chat);
    }

    public ChatFile createChatroom(File f) throws Exception {
        ChatFile chat = new ChatFile(f);
        chat.createNewFile();
        String header = "Welcome to chatroom " + chat.getNameNoExtension() + '\n';
        chat.append(header);

        addChat(chat);
        return chat;
    }

    public ArrayList<ChatFile> getOpenChats() {
        return openChats;
    }

    public void setUsername(String name) {
        username = name;
    }
}
